"use client";
import { useState, useEffect } from "react";
import { adminUserAPI } from "@/lib/api";
import { 
  Card, Table, Button, Input, Space, Modal, Form, 
  Select, Switch, Avatar, Tag, Tooltip, Popconfirm 
} from "antd";
import { useMessage } from '@/hooks/useMessage';
import {
  UserOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined
} from "@ant-design/icons";
import AdminLayout from "@/components/AdminLayout";
import { ColumnsType } from "antd/es/table";

const { Search } = Input;
const { Option } = Select;

interface User {
  id: number;
  username: string;
  email: string;
  role: string;
  status: boolean;
  createdAt: string;
  lastLogin: string;
}

export default function UsersManagement() {
  const message = useMessage();
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [form] = Form.useForm();

  useEffect(() => {
    fetchUsers();
  }, []);

  const fetchUsers = async () => {
    setLoading(true);
    try {
      const res = await adminUserAPI.getUsers();
      if (res.success && Array.isArray(res.data)) {
        setUsers(res.data.map((u: User) => ({
          ...u,
          key: u.id,
        })));
      } else {
        setUsers([]);
      }
    } catch {
      setUsers([]);
    }
    setLoading(false);
  };

  const handleAddUser = () => {
    setEditingUser(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEditUser = (record: User) => {
    setEditingUser(record);
    form.setFieldsValue({
      ...record,
      password: '', // 清空密码字段
    });
    setIsModalVisible(true);
  };

  const handleDeleteUser = async (id: number) => {
    try {
      await adminUserAPI.deleteUser(id);
      message.success("用户删除成功");
      fetchUsers();
    } catch {
      message.error("删除失败");
    }
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      // 仅有密码时才传递
      const submitValues = { ...values };
      if (!submitValues.password) delete submitValues.password;
      if (editingUser) {
        await adminUserAPI.updateUser(editingUser.id, submitValues);
        message.success("用户更新成功");
      } else {
        await adminUserAPI.createUser(submitValues);
        message.success("用户添加成功");
      }
      setIsModalVisible(false);
      fetchUsers();
    } catch {
      message.error("操作失败");
    }
  };

  const columns: ColumnsType<User> = [
    {
      title: "用户ID",
      dataIndex: "id",
      key: "id",
      width: 80,
    },
    {
      title: "头像",
      dataIndex: "avatar",
      key: "avatar",
      width: 60,
      render: () => <Avatar icon={<UserOutlined />} />,
    },
    {
      title: "用户名",
      dataIndex: "username",
      key: "username",
    },
    {
      title: "邮箱",
      dataIndex: "email",
      key: "email",
    },
    {
      title: "角色",
      dataIndex: "role",
      key: "role",
      render: (role: string) => {
        const colorMap: Record<string, string> = {
          admin: "red",
          editor: "blue",
          user: "green"
        };
        const roleMap: Record<string, string> = {
          admin: "管理员",
          editor: "编辑",
          user: "普通用户"
        };
        return <Tag color={colorMap[role]}>{roleMap[role] || role}</Tag>;
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status: boolean) => (
        <Tag color={status ? "green" : "red"}>
          {status ? "启用" : "禁用"}
        </Tag>
      ),
    },
    {
      title: "注册时间",
      dataIndex: "createdAt",
      key: "createdAt",
      render: (text: string) => text ? new Date(text).toLocaleString('zh-CN', { hour12: false }).replace(/\//g, '-') : '',
    },
    {
      title: "最后登录",
      dataIndex: "lastLogin",
      key: "lastLogin",
      render: (text: string) => text ? new Date(text).toLocaleString('zh-CN', { hour12: false }).replace(/\//g, '-') : '从未登录',
    },
    {
      title: "操作",
      key: "action",
      width: 150,
      render: (_: unknown, record: User) => (
        <Space size="small">
          <Tooltip title="编辑">
            <Button 
              type="text" 
              icon={<EditOutlined />} 
              onClick={() => handleEditUser(record)}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个用户吗？"
            onConfirm={() => handleDeleteUser(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button 
                type="text" 
                danger 
                icon={<DeleteOutlined />} 
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <AdminLayout>
      <Card>
        <div style={{ marginBottom: 16, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <h2>用户管理</h2>
          <Space>
            <Search
              placeholder="搜索用户"
              style={{ width: 200 }}
              onSearch={(value) => console.log(value)}
            />
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAddUser}>
              添加用户
            </Button>
          </Space>
        </div>
        <Table
          columns={columns}
          dataSource={users}
          loading={loading}
          rowKey="id"
          locale={{ emptyText: loading ? '加载中...' : '--' }}
          pagination={{
            total: users.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>

      <Modal
        title={editingUser ? "编辑用户" : "添加用户"}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{ status: true, role: "user" }}
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item
            name="password"
            label="新密码"
            rules={editingUser ? [] : [{ required: true, message: '请输入密码' }]}
          >
            <Input.Password placeholder="留空则不修改密码" />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { type: "email", message: "请输入有效的邮箱地址" }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          <Form.Item
            name="role"
            label="角色"
            rules={[{ required: true, message: "请选择角色" }]}
          >
            <Select placeholder="请选择角色">
              <Option value="admin">管理员</Option>
              <Option value="editor">编辑</Option>
              <Option value="user">普通用户</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            valuePropName="checked"
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>
        </Form>
      </Modal>
    </AdminLayout>
  );
}